import { NextRequest, NextResponse } from 'next/server';
import { templateImportService } from '@/lib/template-import';
import { verifyAuth } from '@/lib/auth-middleware';

export async function POST(request: NextRequest) {
  try {
    const authResult = await verifyAuth();
    
    if (!authResult.success || !authResult.user) {
      return NextResponse.json({
        success: false,
        error: authResult.error
      }, { status: authResult.status || 401 });
    }

    // 解析表单数据
    const formData = await request.formData();
    const file = formData.get('file') as File;
    const classificationCode = formData.get('classificationCode') as string;
    const validateOnly = formData.get('validateOnly') === 'true';
    const skipDuplicates = formData.get('skipDuplicates') === 'true';

    if (!file) {
      return NextResponse.json({
        success: false,
        error: '未上传文件'
      }, { status: 400 });
    }

    if (!classificationCode) {
      return NextResponse.json({
        success: false,
        error: '缺少分类代码参数'
      }, { status: 400 });
    }

    // 验证文件类型
    const allowedTypes = [
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      'application/vnd.ms-excel'
    ];
    
    if (!allowedTypes.includes(file.type)) {
      return NextResponse.json({
        success: false,
        error: '只支持Excel文件 (.xlsx, .xls)'
      }, { status: 400 });
    }

    // 检查文件大小（限制10MB）
    if (file.size > 10 * 1024 * 1024) {
      return NextResponse.json({
        success: false,
        error: '文件大小不能超过10MB'
      }, { status: 400 });
    }

    // 读取文件内容
    const arrayBuffer = await file.arrayBuffer();

    // 导入数据
    const importResult = await templateImportService.importTemplateData(arrayBuffer, {
      classificationCode,
      userRole: authResult.user.role_code,
      validateOnly,
      skipDuplicates
    });

    return NextResponse.json({
      success: true,
      data: importResult
    });

  } catch (error) {
    console.error('导入数据失败:', error);
    return NextResponse.json({
      success: false,
      error: error instanceof Error ? error.message : '导入数据失败'
    }, { status: 500 });
  }
}